package com.twotwoshop.service.order.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.twotwoshop.domin.common.dtos.ResponseResult;
import com.twotwoshop.domin.common.enums.AppHttpCodeEnum;
import com.twotwoshop.domin.order.pojo.Order;
import com.twotwoshop.domin.order.pojo.OrderDetail;
import com.twotwoshop.domin.order.vos.OrderDetailVo;
import com.twotwoshop.service.order.mapper.OrderDetailMapper;
import com.twotwoshop.service.order.mapper.OrderMapper;
import com.twotwoshop.service.order.service.IOrderDetailService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * <p>
 * 订单详情表 服务实现类
 * </p>
 *
 * @author 王帅
 * @since 2024-12-24
 */
@Service
@RequiredArgsConstructor
public class OrderDetailServiceImpl extends ServiceImpl<OrderDetailMapper, OrderDetail> implements IOrderDetailService {



    private final OrderDetailMapper orderDetailMapper;

    private final OrderMapper orderMapper;

    /**
     * 查询订单详情
     *
     * @param orderId
     * @return
     */
    @Override
    public ResponseResult orderService(Long orderId) {

        //1.检查参数
        if (orderId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"查询订单详情参数为空");
        }

        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<OrderDetail>();
        queryWrapper.eq(OrderDetail::getOrderId, orderId);

        OrderDetail orderDetail = orderDetailMapper.selectOne(queryWrapper);
        if (orderDetail == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"查询订单详情信息错误");
        }

        //查询订单状态
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"订单不存在");
        }

        OrderDetailVo orderDetailVo = BeanUtil.copyProperties(orderDetail, OrderDetailVo.class);
        orderDetailVo.setStatus(order.getStatus());
        //设置过期时间（例如30分钟后）

        // 假设 order 是已经存在的订单对象，orderDetailVo 是要设置的订单详情对象
        LocalDateTime createTime = order.getCreateTime();
        // 将 LocalDateTime 转换为 Instant
        Instant createInstant = createTime.atOffset(ZoneOffset.UTC).toInstant();
        // 将 Instant 转换为毫秒时间戳
        long createTimeMillis = createInstant.toEpochMilli();
        // 设置过期时间为创建时间加上30分钟
        orderDetailVo.setExpireTime(createTimeMillis);

        return ResponseResult.okResult(orderDetailVo);
    }

}
